package com.huangsm.concurrence.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 限制并发流量
 * @author huang
 * @PACKAGE_NAME com.huangsm.concurrence.demo
 * @PROJECT_NAME concurrence
 * @date 2019/2/15
 */
public class LimitDemo {
    /**
     * 在高并发的场景下，也可以用来限制接口流量，超过并发的数量的阈值进行熔断等操作
     */
    public static void main(String[] args) {
        LimitDemo limitDemo=new LimitDemo();
        ExecutorService executorService =
                Executors.newFixedThreadPool(100);
        Runnable runnable=null;
        for (int i = 0; i < 1000; i++) {
             runnable = () -> limitDemo.invokeMethod();
            executorService.execute(runnable);
        }

    }
    private AtomicLong atomicLong=new AtomicLong(0);
    private void invokeMethod(){
        try{
            long current = atomicLong.incrementAndGet();
            Long limit=10L;
            if (current>limit){
                System.out.println("拒绝访问");
            }else{
                System.out.println("处理请求");
            }
        }finally {
            atomicLong.decrementAndGet();
        }
    }
}
